package com.iter.devbox.lang;

public class MyThreadLocal {

	//student变量值被修改了，但ThreadLocal与当前线程绑定了，不会被修改
	public static void main(String[] args) {
		ThreadLocal<Integer> local = new ThreadLocal<Integer>();
		Student s = new Student();
		
		Thread t1 = new Thread(new MyThrad (local, s));
		Thread t2 = new Thread(new MyThrad1 (local, s));
		t1.start();
		t2.start();
		
	}
}

class MyThrad implements Runnable {
	
	private ThreadLocal<Integer> local;
	
	private Student s;
	
	public MyThrad(ThreadLocal<Integer> local, Student s) {
		this.local = local;
		this.s = s;
	}
	
	@Override
	public void run() {
		this.s.setAge(10);
		this.s.setName("张三0");
		local.set(0);
		System.out.println(Thread.currentThread().getName() + "-->index:" + local.get() + " -->age:" + this.s.getAge());
	}
}

class MyThrad1 implements Runnable {
	private ThreadLocal<Integer> local;
	
	private Student s;
	
	public MyThrad1(ThreadLocal<Integer> local, Student s) {
		this.local = local;
		this.s = s;
	}
	
	@Override
	public void run() {
		this.s.setAge(11);
		this.s.setName("张三1");
		local.set(1);
		System.out.println(Thread.currentThread().getName() + "-->index:" + local.get() + " -->age:" + this.s.getAge());
	}
}

class Student {
	
	private int age;
	
	private String name;

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}
